package server.main;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class StartServer {

	public static void main(String[] args) {
		Socket socket = null;
		ServerSocket serverSocket = null;
		ServerThreadHandle serverThreadHandle = null;
		int count = 0;
		boolean enableWaiting = true;

		// create server
		System.out.println("Server is started. Waiting for connecting client ... !");

		try {
			serverSocket = new ServerSocket(4444);
		} catch (IOException e) {
			System.err.println("Could not listen on port: 4444.");
			System.exit(-1);
		}

		// Wait for a request connection
		while (enableWaiting) {
			try {
				socket = serverSocket.accept();
				serverThreadHandle = new ServerThreadHandle(socket, count);

				System.out.println("Start thread: " + count);
				count++;
				serverThreadHandle.start();
			} catch (IOException e) {
				System.err.println("No available client.");
				enableWaiting = false;
			}
		}

		try {
			serverSocket.close();
		} catch (IOException e) {
			System.out.println("Close server socket failed.");
		}

	}
}
